using System.Web.UI.WebControls;

namespace System.Web.Core
{
    public class ValuedDropDownList : DropDownList, IValuedControl
    {
        public string Value
        {
            get 
            {
                if (this.SelectedItem == null || string.IsNullOrEmpty(this.SelectedItem.Value))
                {
                    return GetFormValue();
                }
                else
                {
                    try
                    {
                        if (int.Parse(this.SelectedItem.Value) <= 0)
                        {
                            return GetFormValue();
                        }
                    }
                    catch
                    {
                        return GetFormValue();
                    }
                    return this.SelectedItem.Value;
                }
            }
            set
            {
                if (this.Items.Count == 0 || value == null)
                {
                    return;
                }

                ListItem item = this.Items.FindByValue(value);
                if (item != null)
                {
                    item.Selected = true;
                }
                else
                {
                    this.SelectedIndex = -1;
                }
            }
        }

        private string GetFormValue()
        {
            if (!string.IsNullOrEmpty(this.Page.Request.Form[this.UniqueID]))
            {
                return this.Page.Request.Form[this.UniqueID];
            }
            return string.Empty;
        }
    }

}
